
#include "actor.h"
#include "byte_buffer.h"
#include "framework.h"
#include <sstream>

as::md::Actor::Actor(FrameWork *fw, const char *name)
	:fw_(fw), name_(name)
{
	cache_packet_ = std::make_shared<ByteBuffer>();
	cache_packet_->make_writeable_bytes(1024);
	fw_->RegisterActor(this);
}

as::md::Actor::~Actor()
{
	fw_->UnregisterActor(this);
}

void as::md::Actor::SetAddr(MailPos addr)
{
	addr_ = addr;
}

as::md::MailPos& as::md::Actor::GetAddr()
{
	return addr_;
}

uint32 as::md::Actor::GetPriKey()
{
	return fw_->GetPriKey();
}

void as::md::Actor::Send(ByteBufferPtr &buf, MailPos &to)
{
	fw_->Send(buf, GetAddr(), to);
}

void as::md::Actor::SendAll(ByteBufferPtr &buf)
{
	fw_->SendAll(buf, GetAddr());
}

void as::md::Actor::Send(ByteBufferPtr &buf, const char *toname, int toFrameId)
{
	fw_->Send(buf, GetAddr(), toname, toFrameId);
}

void as::md::Actor::SetActorHandle(as::md::Actor::ActorHandle fun)
{
	fun_ = fun;
}

void as::md::Actor::ActorMsg(ByteBufferPtr &buf, MailPos &addr)
{
	if (fun_)
	{
		fun_(buf, addr);
	}
}

std::string as::md::Actor::GetAddrStr()
{
	std::stringstream ss;
	ss << "name:" << name_ << " addr:" << addr_.frame_id_ << "-" << addr_.page_ << "-" << addr_.index_;
	return ss.str();
}

void as::md::Actor::Send(ByteBufferPtr &buf, Actor *to)
{
	MailPos addr = to->GetAddr();
	Send(buf, addr);
}

ByteBufferPtr as::md::Actor::GetPacket()
{
	cache_packet_->reset();
	return cache_packet_;
}
